package com.wtb.javatool.service.impl;

import com.wtb.javatool.dao.TeamMapper;
import com.wtb.javatool.dto.UserDto;
import com.wtb.javatool.entity.Team;
import com.wtb.javatool.service.TeamService;
import com.wtb.javatool.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TeamServiceImpl implements TeamService {
    @Autowired
    private TeamMapper teamMapper;
    
    @Autowired
    private UserService userService;

    /**
     * 添加小组到班级
     * 注意：新创建的小组没有组长，需要后续通过updateTeamLeader方法设置
     *
     * @param classId  班级ID
     * @param teamName 小组名称
     */
    @Override
    public void addTeam(Long classId, String teamName) {
        System.out.println("创建新小组: " + teamName + " 到班级ID: " + classId);
        Team team = new Team();
        team.setTeamName(teamName);
        // 不设置组长，组长需要后续从小组成员中选择设置
        team.setTeamLeaderId(null);
        teamMapper.insertTeam(team);
        teamMapper.insertClassTeamRef(classId, team.getTeamId());
        System.out.println("成功创建小组: " + teamName + ", ID: " + team.getTeamId() + ", 未设置组长");
    }

    /**
     * 从小组中移除学生
     * 注意：这个方法不会删除学生的班级关联，只会将学生从小组中移除（将小组ID置为NULL）
     *
     * @param teamId 要删除的小组ID
     */
    @Override
    public void deleteTeam(Long teamId) {
        System.out.println("正在删除小组 ID: " + teamId + "的关联关系");
        teamMapper.deleteClassTeamRef(teamId);
        System.out.println("已成功删除小组 ID: " + teamId + "与班级的关联");
    }

    /**
     * 设置小组组长
     *
     * @param teamId 小组ID
     * @param userId 用户ID，即将被设为组长的学生ID
     */
    @Override
    public void updateTeamLeader(Long teamId, Long userId) {
        System.out.println("设置小组 ID: " + teamId + " 的组长为用户 ID: " + userId);
        teamMapper.updateTeamLeader(teamId, userId);
        System.out.println("成功设置小组 ID: " + teamId + " 的组长为用户 ID: " + userId);
    }
    
    /**
     * 根据小组ID查询小组成员
     *
     * @param teamId 小组ID
     * @return 小组成员列表
     */
    @Override
    public List<UserDto> findStudentsByTeamId(Long teamId) {
        return userService.findStudentsByTeamId(teamId);
    }
}
